package com.smsp.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.smsp.common.Const;
import com.smsp.common.ServerResponse;
import com.smsp.dao.JedisClient;
import com.smsp.dao.TempletMapper;
import com.smsp.entity.Templet;
import com.smsp.entity.User;
import com.smsp.service.TempletService;
import com.smsp.util.AssemblingID;
import com.smsp.util.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;


@Service("TempletService")
@Transactional
public class TempletServiceImpl implements TempletService {
    public Logger logger = LoggerFactory.getLogger(TempletServiceImpl.class);
    @Autowired
    private TempletMapper templetMapper;
    @Autowired
    private JedisClient jedisClient;

    @Override
    public ServerResponse insertTemplet(Templet templet, User user) {

        Templet templet1 = templetMapper.selectByTempletSign(templet.getTempletSign());
        if(templet1 !=null && templet1.getUserId().intValue()!=user.getId().intValue()){
            logger.debug("签名："+templet.getTempletSign()+"被占用");
            return ServerResponse.createByErrorCodeMessage(Const.ERROR_USER_NEED_LOGIN,"模板签名不可用");
        }

        if(templet1 !=null && templet1.getUserId().intValue()==user.getId().intValue()){
            /*签名一致，且为当前用户创建*/
            templet.setTempletExtno(templet1.getTempletExtno());
        }
        if(templet1 == null){
            String templetExtno = templetMapper.selectMaxTemplateExtno();
            if(templetExtno==null){
                /*第一条*/
                templet.setTempletExtno(Const.FIRST_TEMPLATE_EXTNO);
            }else {

                DecimalFormat df=new DecimalFormat("000000");
                String extNo=df.format( Integer.parseInt(templetExtno)+1);
                templet.setTempletExtno(extNo);
            }
        }

        String templetID = AssemblingID.AssemblingTempletID(user.getId());
        templet.setTempletNo(templetID);
        templet.setTempletStatus(Const.STATUS_TEMPLEAT_NOT_EXAMINE);//初始化审核状态
        templet.setCreateTime(new Date());
        templet.setUserId(user.getId());
        if (templetMapper.insertSelective(templet) > 0) {
            logger.info("成功创建模板",templet);
            jedisClient.set(Const.REDIS_PREFIX_TEMPLAET+templet.getTempletNo(),JsonUtils.objectToJson(templet));
            jedisClient.expire(templetID,120000);
            return ServerResponse.cerateBySuccessMessage("模板创建成功");
        }
        logger.error("创建模板失败",templet);
        return ServerResponse.createByErrorMessage("模板创建失败");
    }

    @Override
    public ServerResponse deleteTemplet(Templet templet){
        if (templetMapper.deleteByPrimaryKey(templet.getId())> 0) {
            jedisClient.del(Const.REDIS_PREFIX_TEMPLAET+templet.getTempletNo());
            logger.info("成功删除模板",templet);
            return ServerResponse.cerateBySuccessMessage("成功");
        }
        logger.error("删除模板失败",templet);
        return ServerResponse.createByErrorMessage("模板删除失败");
    }

    @Override
    public ServerResponse updateTemplet(Templet templet){
        if (templetMapper.updateByPrimaryKey(templet)>0) {
            jedisClient.set(Const.REDIS_PREFIX_TEMPLAET+templet.getTempletNo(),JsonUtils.objectToJson(templet));
            logger.info("成功更新信息日志");
            return ServerResponse.createBySuccess();
        }
        logger.error("更新日志失败");
        return ServerResponse.createByErrorMessage("失败");
    }


    @Override
    public ServerResponse selectAllTemplet(){
        List<Templet> templetList= templetMapper.selectAllTemplate();
        if (templetList != null){
            logger.info("成功查询");
            return ServerResponse.cerateBySuccess(templetList);
        }
        logger.error("失败查询");
        return ServerResponse.createByErrorMessage("数据查询失败");
    }

    @Override
    public ServerResponse updateTempletStatus(Templet templet){

        if(templet==null ||(templet!=null && templet.getId()==null)){
            logger.debug("参数传入错误或id is null",templet);
            return ServerResponse.createByErrorMessage("参数错误");
        }
        if(templetMapper.updateByPrimaryKeySelective(templet)>0){
            jedisClient.set(Const.REDIS_PREFIX_TEMPLAET+templet.getTempletNo(),JsonUtils.objectToJson(templet));
            logger.info("模板审核成功",templet);
            return ServerResponse.cerateBySuccessMessage("操作成功");
        }
        return ServerResponse.createByErrorMessage("操作失败");
    }

    @Override
    public ServerResponse selectPassTempletByUserId(Integer userId){
        if(userId==null){
            logger.debug("参数传入错误或id is null",userId);
            return ServerResponse.createByErrorMessage("参数错误");
        }
       List<Templet> templetList = templetMapper.selectPassListByUserId(userId);

        return ServerResponse.cerateBySuccess(templetList);

    }

    @Override
    public ServerResponse selectListByUserId(Integer userId){
        if(userId==null){
            logger.debug("参数传入错误或id is null",userId);
            return ServerResponse.createByErrorMessage("参数错误");
        }
        List<Templet> templetList = templetMapper.selectListByUserId(userId);
        return ServerResponse.cerateBySuccess(templetList);
    }

    @Override
    public PageInfo<Templet> findMessageDetailByPage(int page, int pageSize) {
        PageHelper.startPage(page, pageSize);
        List<Templet> list = templetMapper.selectAllTemplate();
        return new PageInfo<Templet>(list);
    }

}

